<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />





  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "6d134c3b"
    });
  daovoice('update');
  </script>




















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.1" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.4.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.4.1">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.1" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.4.1',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="Python是一门强大且灵活的脚本语言，依赖众多强大的第三方库可以大大提高工作效率。在网络编程和自动化领域Python有着大量的实际应用，可以用C语言编写Python底层的实现库，然后通过Python简洁的语法，在实际工作中快速达到为所欲为的目的。由于最近工作需要配合测试人员进行一些数据接口的大量访问和数据的批量生成，为了能够高效的完成工作我选择了Python。工作中一些零散的任务我也基本上是以P">
<meta name="keywords" content="Python">
<meta property="og:type" content="article">
<meta property="og:title" content="使用Python提高工作效率之Requests库">
<meta property="og:url" content="https://www.lanshiqin.com/db2a9d2b/index.html">
<meta property="og:site_name" content="蓝士钦">
<meta property="og:description" content="Python是一门强大且灵活的脚本语言，依赖众多强大的第三方库可以大大提高工作效率。在网络编程和自动化领域Python有着大量的实际应用，可以用C语言编写Python底层的实现库，然后通过Python简洁的语法，在实际工作中快速达到为所欲为的目的。由于最近工作需要配合测试人员进行一些数据接口的大量访问和数据的批量生成，为了能够高效的完成工作我选择了Python。工作中一些零散的任务我也基本上是以P">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-01-30T11:44:45.702Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="使用Python提高工作效率之Requests库">
<meta name="twitter:description" content="Python是一门强大且灵活的脚本语言，依赖众多强大的第三方库可以大大提高工作效率。在网络编程和自动化领域Python有着大量的实际应用，可以用C语言编写Python底层的实现库，然后通过Python简洁的语法，在实际工作中快速达到为所欲为的目的。由于最近工作需要配合测试人员进行一些数据接口的大量访问和数据的批量生成，为了能够高效的完成工作我选择了Python。工作中一些零散的任务我也基本上是以P">



  <link rel="alternate" href="/atom.xml" title="蓝士钦" type="application/atom+xml" />




  <link rel="canonical" href="https://www.lanshiqin.com/db2a9d2b/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>使用Python提高工作效率之Requests库 | 蓝士钦</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

  <script src="/js/src/photoswipe.js?v="></script>
  <script src="/js/src/photoswipe-ui-default.js?v="></script>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">蓝士钦</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">编程是一种信仰</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-相册">
    <a href="/photos/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />相册</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.lanshiqin.com/db2a9d2b/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="蓝士钦">
      <meta itemprop="description" content="编程是一种信仰">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="蓝士钦">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">使用Python提高工作效率之Requests库
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-01-05 11:52:01" itemprop="dateCreated datePublished" datetime="2019-01-05T11:52:01+08:00">2019-01-05</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-01-30 19:44:45" itemprop="dateModified" datetime="2019-01-30T19:44:45+08:00">2019-01-30</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Python是一门强大且灵活的脚本语言，依赖众多强大的第三方库可以大大提高工作效率。在网络编程和自动化领域Python有着大量的实际应用，可以用C语言编写Python底层的实现库，然后通过Python简洁的语法，在实际工作中快速达到为所欲为的目的。由于最近工作需要配合测试人员进行一些数据接口的大量访问和数据的批量生成，为了能够高效的完成工作我选择了Python。工作中一些零散的任务我也基本上是以Python来完成，我决定分为几篇文章来对一些基本库的使用进行记录，方便日后查阅以及学习。本章节我先以比较常用的request库开始。</p>
<a id="more"></a>
<h1 id="快速上手"><a href="#快速上手" class="headerlink" title="快速上手"></a>快速上手</h1><h2 id="发送请求"><a href="#发送请求" class="headerlink" title="发送请求"></a>发送请求</h2><p>第一步：导入requests模块<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> requests</span><br></pre></td></tr></table></figure></p>
<p>第二步：请求网络资源<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>r = requests.get(<span class="string">'https://www.lanshiqin.com'</span>)</span><br></pre></td></tr></table></figure></p>
<p>使用方式非常简单，只需要引入requests的模块，然后发送GET请求只需要一行代码搞定。<br>上述步骤将会使用GET请求网站并且将响应的Response对象赋值给r。</p>
<p>Requests还支持各种RESTFul方式的请求<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>r = requests.post(<span class="string">'http://httpbin.org/post'</span>, data=&#123;<span class="string">'key'</span>: <span class="string">'value'</span>&#125;)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>r = requests.put(<span class="string">'http://httpbin.org/put'</span>, data=&#123;<span class="string">'key'</span>: <span class="string">'value'</span>&#125;)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>r = requests.delete(<span class="string">'http://httpbin.org/delete'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>r = requests.head(<span class="string">'http://httpbin.org/get'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>r = requests.options(<span class="string">'http://httpbin.org/get'</span>)</span><br></pre></td></tr></table></figure></p>
<h2 id="响应内容"><a href="#响应内容" class="headerlink" title="响应内容"></a>响应内容</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> requests</span><br><span class="line">r = requests.get(<span class="string">'https://api.github.com/'</span>)</span><br><span class="line">print(r.text)</span><br><span class="line"><span class="comment"># 输出文本内容 &#123;"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":"https://github.com/settings/connections/applications&#123;/client_id&#125;","authorizations_url":"https://api.github.com/authorizations","code_search_url":"https://api.github.com/search/code?q=&#123;query&#125;&#123;&amp;page,per_page,sort,order&#125;","commit_search_url":"https://api.github.com/search/commits?q=&#123;query&#125;&#123;&amp;page,per_page,sort,order&#125;","emails_url":"https://api.github.com/user/emails","emojis_url":"https://api.github.com/emojis","events_url":"https://api.github.com/events","feeds_url":"https://api.github.com/feeds","followers_url":"https://api.github.com/user/followers","following_url":"https://api.github.com/user/following&#123;/target&#125;","gists_url":"https://api.github.com/gists&#123;/gist_id&#125;","hub_url":"https://api.github.com/hub","issue_search_url":"https://api.github.com/search/issues?q=&#123;query&#125;&#123;&amp;page,per_page,sort,order&#125;","issues_url":"https://api.github.com/issues","keys_url":"https://api.github.com/user/keys","notifications_url":"https://api.github.com/notifications","organization_repositories_url":"https://api.github.com/orgs/&#123;org&#125;/repos&#123;?type,page,per_page,sort&#125;","organization_url":"https://api.github.com/orgs/&#123;org&#125;","public_gists_url":"https://api.github.com/gists/public","rate_limit_url":"https://api.github.com/rate_limit","repository_url":"https://api.github.com/repos/&#123;owner&#125;/&#123;repo&#125;","repository_search_url":"https://api.github.com/search/repositories?q=&#123;query&#125;&#123;&amp;page,per_page,sort,order&#125;","current_user_repositories_url":"https://api.github.com/user/repos&#123;?type,page,per_page,sort&#125;","starred_url":"https://api.github.com/user/starred&#123;/owner&#125;&#123;/repo&#125;","starred_gists_url":"https://api.github.com/gists/starred","team_url":"https://api.github.com/teams","user_url":"https://api.github.com/users/&#123;user&#125;","user_organizations_url":"https://api.github.com/user/orgs","user_repositories_url":"https://api.github.com/users/&#123;user&#125;/repos&#123;?type,page,per_page,sort&#125;","user_search_url":"https://api.github.com/search/users?q=&#123;query&#125;&#123;&amp;page,per_page,sort,order&#125;"&#125;</span></span><br></pre></td></tr></table></figure>
<p><code>r.text</code>输出文本内容的编码是Request进行自动推断的，可以使用<code>r.encoding</code>来输出实际响应的编码，也可以自己自定Response的编码<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">r.encoding = <span class="string">'utf-8'</span></span><br></pre></td></tr></table></figure></p>
<h3 id="二进制响应内容"><a href="#二进制响应内容" class="headerlink" title="二进制响应内容"></a>二进制响应内容</h3><p>对于非文本请求，可以用字节byte的方式来访问响应内容<br>Request库提供了<code>r.content</code>来访问二进制响应内容<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"><span class="keyword">from</span> PIL <span class="keyword">import</span> Image</span><br><span class="line"><span class="keyword">from</span> io <span class="keyword">import</span> BytesIO</span><br><span class="line"><span class="comment"># 请求图片</span></span><br><span class="line">r = requests.get(<span class="string">'https://github.githubassets.com/images/icons/emoji/unicode/1f947.png?v8'</span>)</span><br><span class="line"><span class="comment"># 打开图片</span></span><br><span class="line">i = Image.open(BytesIO(r.content))</span><br><span class="line"><span class="comment"># 保存图片</span></span><br><span class="line">i.save(<span class="string">'1f947.png'</span>, <span class="string">'png'</span>)</span><br></pre></td></tr></table></figure></p>
<h3 id="原始响应内容"><a href="#原始响应内容" class="headerlink" title="原始响应内容"></a>原始响应内容</h3><p>对于一些文件的下载，可以使用Request库提供的<code>r.raw</code>获取原始响应内容<br>可以使用<code>r.raw.read(1024)</code>指定大小的读取原始内容<br>大多数情况下一般会将原始内容保存为文件<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"><span class="comment"># 请求数据</span></span><br><span class="line">r = requests.get(<span class="string">'https://dl.pstmn.io/download/latest/osx'</span>, stream=<span class="keyword">True</span>)</span><br><span class="line">print(r.raw.read(<span class="number">10</span>))</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'osx.zip'</span>, <span class="string">'wb'</span>) <span class="keyword">as</span> fd:</span><br><span class="line">    <span class="keyword">for</span> chunk <span class="keyword">in</span> r.iter_content(<span class="number">1024</span>):</span><br><span class="line">        fd.write(chunk)</span><br></pre></td></tr></table></figure></p>
<p>requests请求时要指定属性值<code>stream=True</code>,通过Requests库提供的<code>iter_content</code>方法可以指定一次读取多少数据</p>
<h2 id="更加复杂的请求"><a href="#更加复杂的请求" class="headerlink" title="更加复杂的请求"></a>更加复杂的请求</h2><h3 id="请求头参数"><a href="#请求头参数" class="headerlink" title="请求头参数"></a>请求头参数</h3><p>以我个人的使用场景作为参考，使用请求头参数最多是爬虫程序，因为要伪装成正常的用户请求，所以不得不在请求头参数中指定UA和Cookie等值。除此之外，对于正常的程序访问来说我们一般也需要一些认证授权信息，可以通过自定义请求头参数来进行验证。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"></span><br><span class="line">url = <span class="string">'https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=2019-01-07&amp;leftTicketDTO.from_station=XMS&amp;leftTicketDTO.to_station=YXS&amp;purpose_codes=ADULT'</span></span><br><span class="line">headers = &#123;</span><br><span class="line">    <span class="string">'accept'</span>: <span class="string">'*/*'</span>,</span><br><span class="line">    <span class="string">'accept-encoding'</span>: <span class="string">'gzip, deflate, br'</span>,</span><br><span class="line">    <span class="string">'accept-language'</span>: <span class="string">'zh-CN,zh;q=0.9,en;q=0.8'</span>,</span><br><span class="line">    <span class="string">'cache-control'</span>: <span class="string">'no-cache'</span>,</span><br><span class="line">    <span class="string">'cookie'</span>: <span class="string">'JSESSIONID=165AEDA56401B93F15E336494663D93E; tk=eZwgZIZASH0T-_CHKxmQrHzn0XZAtbknB1gk02D_ONMmk1110; RAIL_EXPIRATION=1546917370307; RAIL_DEVICEID=d0WOu4qSJ_ujU4sVmDaD6LfXgFfxHTWIBX__FHRtRH7o4E_3UvHcp86Iv2qCOFoEiDAh-ihWW2e6s7RnINhR1Ff8oR3In-wiOPokEhTyh1X-zci59jSrdIxTarXFrtWu03bxxzpuO0k8dfaKhCC3njv8PjH9mPtp; BIGipServerpassport=887619850.50215.0000; route=c5c62a339e7744272a54643b3be5bf64; BIGipServerotn=284164618.38945.0000; BIGipServerpool_passport=300745226.50215.0000; _jc_save_fromStation=%u53A6%u95E8%2CXMS; _jc_save_toStation=%u5C24%u6EAA%2CYXS; _jc_save_toDate=2019-01-06; _jc_save_wfdc_flag=dc; current_captcha_type=Z; _jc_save_fromDate=2019-01-07'</span>,</span><br><span class="line">    <span class="string">'if-modified-since'</span>: <span class="string">'0'</span>,</span><br><span class="line">    <span class="string">'referer'</span>: <span class="string">'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc&amp;fs=%E5%8E%A6%E9%97%A8,XMS&amp;ts=%E5%B0%A4%E6%BA%AA,YXS&amp;date=2019-01-06&amp;flag=N,N,Y'</span>,</span><br><span class="line">    <span class="string">'user-agent'</span>: <span class="string">'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'</span>,</span><br><span class="line">    <span class="string">'x-requested-with'</span>: <span class="string">'XMLHttpRequest'</span></span><br><span class="line">&#125;</span><br><span class="line">r = requests.get(url=url, headers=headers)</span><br><span class="line">print(r.text)</span><br></pre></td></tr></table></figure></p>
<p>上面的请求头参数，是我用Chrome浏览器访问12306购票网站，然后在开发者模式下查看网络请求得到的数据，通过请求头参数就可以完美的模拟浏览器的请求，服务端将无法区分出到底是来自用户正常的浏览器，还是一个自动化的脚步程序。通过这些特性我们可以做一些小工具方便自己。</p>
<h3 id="POST请求参数"><a href="#POST请求参数" class="headerlink" title="POST请求参数"></a>POST请求参数</h3><p>在发起请求的时候设置<code>data</code>参数值来指定请求参数，data默认是一个表单数据格式，键值对表示要传送的参数名和对应的参数值。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"></span><br><span class="line"><span class="comment"># 请求数据</span></span><br><span class="line">data = &#123;</span><br><span class="line">    <span class="string">'CMD'</span>: <span class="string">'102'</span>,</span><br><span class="line">    <span class="string">'CITYNAME'</span>: <span class="string">'厦门市'</span>,</span><br><span class="line">    <span class="string">'KEYWORD'</span>: <span class="string">'641'</span></span><br><span class="line">&#125;</span><br><span class="line">r = requests.post(<span class="string">'https://wx.shenghuoquan.cn/WxBusServer/ApiData.do'</span>, data=data)</span><br><span class="line">print(r.text)</span><br></pre></td></tr></table></figure></p>
<p>如果要传送的格式为json格式，只需要在上述的data参数中指定<code>data=json.dumps(data)</code>即可，使用json需要在头部引入<code>import json</code>,不过最新版的Request库为我们做了自动转换，如果接口接受一个json而不是表单，request库会自动将data转换为json。<br>上面的请求参数和请求地址，是我通过抓包工具得到的，某公交实时查询软件所请求的数据，通过post请求并且带上不同的参数值，可以达到和软件请求一样的效果。由于该软件打开有广告并且我认为一些功能是我用不到的，所以我可以通过抓包分析然后通过Python模拟请求，最终确定想要的数据接口后，自己开发一个基于该接口的App。</p>
<h3 id="POST上传Multipart类型的文件"><a href="#POST上传Multipart类型的文件" class="headerlink" title="POST上传Multipart类型的文件"></a>POST上传Multipart类型的文件</h3><p>通过Post请求上传文件是很常见的场景，在Postman等工具中可以方便的选择文件并且上传到指定地址，使用Python的Request一样很方便<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"></span><br><span class="line">url = <span class="string">'http://httpbin.org/post'</span></span><br><span class="line">files = &#123;<span class="string">'file'</span>: open(<span class="string">'1f947.png'</span>, <span class="string">'rb'</span>)&#125;</span><br><span class="line">r = requests.post(url, files=files)</span><br><span class="line">print(r.text)</span><br></pre></td></tr></table></figure></p>
<p>同样的，在请求的时候指定<code>files</code>参数值为一个打开的文件对象，<code>files = {&#39;file&#39;: open(&#39;1f947.png&#39;, &#39;rb&#39;)}</code>这行代码可以打开<code>1f947.png</code>这个文件作为 <code>file</code>的值。Python的语法优雅到如此简单。</p>
<h1 id="高级用法"><a href="#高级用法" class="headerlink" title="高级用法"></a>高级用法</h1><h3 id="代理"><a href="#代理" class="headerlink" title="代理"></a>代理</h3><p>目前中国大陆有长城防火墙，把Google等一些国外网站给过滤了，正常的直接网络是访问不到的，所以一般都会租用大陆以外的服务器作为代理去替我们访问目标网站，本地-&gt;代理-&gt;Google等被墙的网站。<br>Requests库提供了代理功能，可以在Python中使用代理去访问网络资源，使用方式非常简单<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"></span><br><span class="line">proxies = &#123;</span><br><span class="line">    <span class="string">"http"</span>: <span class="string">"http://127.0.0.1:1087"</span>,</span><br><span class="line">    <span class="string">"https"</span>: <span class="string">"https://127.0.0.1:1087"</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">r = requests.get(<span class="string">"https://www.google.com/"</span>, proxies=proxies)</span><br><span class="line">print(r.text)</span><br></pre></td></tr></table></figure></p>
<p>在请求的时候要指定<code>proxies</code>属性值为我们的代理配置，我使用的是自己搭建的VPN服务器，本地是<code>Shadowsokes</code>客户端，这里的配置需要根据实际情况做修改。<br>代理的使用场景很多，不仅仅是访问被墙的网站，通过一条完美的代理线路以及程序的配合，可以绕过各种限制做各种为所欲为的事情。<br>使用代理比较常见的是爬虫，通过代理池去访问目标网站降低被反爬虫程序的发现。</p>
<h3 id="更多用法"><a href="#更多用法" class="headerlink" title="更多用法"></a>更多用法</h3><p>更多高级用法请访问Requests的官方文档:<br><a href="http://docs.python-requests.org/zh_CN/latest/user/advanced.html#advanced" target="_blank" rel="noopener">http://docs.python-requests.org/zh_CN/latest/user/advanced.html#advanced</a><br>快速入门文档:<br><a href="http://docs.python-requests.org/zh_CN/latest/user/quickstart.html" target="_blank" rel="noopener">http://docs.python-requests.org/zh_CN/latest/user/quickstart.html</a></p>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"><i class="fa fa-tag"></i> Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/c271defc/index.html" rel="next" title="我的2018年个人总结">
                <i class="fa fa-chevron-left"></i> 我的2018年个人总结
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/b4dc6b2c/index.html" rel="prev" title="使用Python提高工作效率之MySQL">
                使用Python提高工作效率之MySQL <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div id="gitalk-container"></div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.png"
                alt="蓝士钦" />
            
              <p class="site-author-name" itemprop="name">蓝士钦</p>
              <p class="site-description motion-element" itemprop="description">编程是一种信仰</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">36</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">7</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">12</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/lanshiqin" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/l18120788756" target="_blank" title="Weibo"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.jianshu.com/u/082f73dac819" target="_blank" title="JianShu"><i class="fa fa-fw fa-heartbeat"></i>JianShu</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:lanshiqin@outlook.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#快速上手"><span class="nav-number">1.</span> <span class="nav-text">快速上手</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#发送请求"><span class="nav-number">1.1.</span> <span class="nav-text">发送请求</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#响应内容"><span class="nav-number">1.2.</span> <span class="nav-text">响应内容</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#二进制响应内容"><span class="nav-number">1.2.1.</span> <span class="nav-text">二进制响应内容</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#原始响应内容"><span class="nav-number">1.2.2.</span> <span class="nav-text">原始响应内容</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#更加复杂的请求"><span class="nav-number">1.3.</span> <span class="nav-text">更加复杂的请求</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#请求头参数"><span class="nav-number">1.3.1.</span> <span class="nav-text">请求头参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#POST请求参数"><span class="nav-number">1.3.2.</span> <span class="nav-text">POST请求参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#POST上传Multipart类型的文件"><span class="nav-number">1.3.3.</span> <span class="nav-text">POST上传Multipart类型的文件</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#高级用法"><span class="nav-number">2.</span> <span class="nav-text">高级用法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#代理"><span class="nav-number">2.0.1.</span> <span class="nav-text">代理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#更多用法"><span class="nav-number">2.0.2.</span> <span class="nav-text">更多用法</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">蓝士钦</span>

  

  
</div>










  <div class="footer-custom">闽ICP备15027850号</div>


        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
	
    

    
  </div>

  

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.4.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.1"></script>
<script src="/js/src/photoswipe.js?v="></script>
<script src="/js/src/photoswipe-ui-default.js?v="></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.1"></script>



  



  










  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
   <script type="text/javascript">
        var gitalk = new Gitalk({
          clientID: '08543e172f1359fce9c3',
          clientSecret: 'a8dd355f95e5035e0266c695e489fa991c9d28e2',
          repo: 'lanshiqin-blog',
          owner: 'lanshiqin',
          admin: ['lanshiqin'],
          id: location.pathname,
          distractionFreeMode: 'true'
        })
        gitalk.render('gitalk-container')           
       </script>

  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
<!-- 页面点击小红心 --> 
<script type="text/javascript" src="/js/src/love.js"></script>
<!--崩溃欺骗-->
<script type="text/javascript" src="/js/src/crash_cheat.js"></script>